#include "fontpreviewwindow.h"

#include <QDragEnterEvent>
#include <QDragMoveEvent>
#include <QDragLeaveEvent>
#include <QDropEvent>
#include <QMimeData>
#include <QTextStream>
#include <QFontDatabase>

#include <QFontDatabase>

#include "fontlistdelegate.h"
#include "fontlistmodel.h"
#include "fontlistview.h"

#include <QVBoxLayout>

FontPreviewWindow::FontPreviewWindow(QWidget *parent) : QMainWindow(parent)
, m_fontModel(new FontListModel(this))
, m_fontView(new FontListView(this))
{
     m_fontView->setItemDelegate(new FontListDelegate(this));
     m_fontView->setModel(m_fontModel);
     m_fontView->setSpacing(5);
     m_fontView->setViewMode(QListView::IconMode);  //设置Item图标显示
     m_fontView->setDragEnabled(false);

    setCentralWidget(m_fontView);

    setAcceptDrops(true);
    resize(670, 400);


    // 第一条数据
    QStandardItem *item = new QStandardItem;
    item->setData(this->font().weight(), FontListModel::FontWeightRole);
    item->setData(this->font().family() + " (默认)", FontListModel::FontFamilyRole);
    m_fontModel->appendRow(item);
    emit m_fontModel->layoutChanged();
}

void FontPreviewWindow::dragEnterEvent(QDragEnterEvent *event)
{
    auto mime = event->mimeData();
    if (mime->hasUrls()) {
        return event->accept();
    }
}

void FontPreviewWindow::dragMoveEvent(QDragMoveEvent *event)
{
    
}

void FontPreviewWindow::dragLeaveEvent(QDragLeaveEvent *event)
{
    
}

void FontPreviewWindow::dropEvent(QDropEvent *event)
{
    auto mime = event->mimeData();
    auto urls = mime->urls();

    foreach (auto url, urls) {
        auto isLocalFile = url.isLocalFile();
        if (isLocalFile) {
            auto fontPath = url.toLocalFile();

            int fontId = QFontDatabase::addApplicationFont(fontPath);
            if (fontId == -1) {
                continue;
            }

            auto fontFamilies = QFontDatabase::applicationFontFamilies(fontId);
            if (fontFamilies.isEmpty()) {
                continue;
            }

            auto fontFamily = fontFamilies.at(0);
            QStandardItem *item = new QStandardItem;
            item->setData(fontId, FontListModel::FontIdRole);
            item->setData(fontFamily, FontListModel::FontFamilyRole);
            m_fontModel->appendRow(item);
            emit m_fontModel->layoutChanged();
        }
    }
}

void FontPreviewWindow::resizeEvent(QResizeEvent *event)
{
    emit m_fontModel->layoutChanged();
}
